#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

#define COMMAND_LEN 1024
#define ARGV_LEN 1024
#define STRTOK_CH " " 
#define DEBUG 1
//const char* STRTOK_CH " ";
#define NONEREDIR 0
#define INPUTREDIR 1
#define OUTPUTREDIR 2
#define APPENDREDIR 3

int redir = NONEREDIR;
char* filename = NULL;
int lastcode = 0;

void printCommand()
{
    printf("[%s@%s %s]# ", getenv("USER"), getenv("HOSTNAME"), getenv("PWD"));
}

int getCommand(char command[])
{
    char* rp = gets(command);
    if(rp == NULL) return 0;
    return strlen(command);
    //char* rp = fgets(command, sizeof command, stdin);
    //if(rp == NULL) return 0;
    //command[strlen(command) - 1] = '\0';
    //printf("%s", command);
    //return strlen(command);
}

int splitCommand(char command[], char* argv[])
{
    int argc = 0;
    argv[argc++] = strtok(command, STRTOK_CH);//第二个参数要是字符串
    while(argv[argc++] = strtok(NULL, STRTOK_CH));
//#ifdef DEBUG
//    for(size_t i = 0; argv[i]; i++)
//        printf("%s\n", argv[i]);//为什么不打印？
//#endif                            //因为return 写到ifdef上面了
    return argc;
}
void excuteSubProcess(char* argv[])
{
    pid_t id = fork();
    if(id < 0)
    {
        return;
    }
    if(id == 0)
    {
        int fd = 0;
        if(redir == INPUTREDIR)
        {
            fd = open(filename, O_RDONLY);
            dup2(fd, 0); 
        }
        else if(redir == OUTPUTREDIR)
        {
            fd = open(filename, O_TRUNC|O_CREAT|O_WRONLY, 0666);
            dup2(fd, 1);
        }
        else if(redir == APPENDREDIR)
        {
            fd = open(filename, O_APPEND|O_CREAT|O_WRONLY, 0666);
            dup2(fd, 1);
        }
        execvp(argv[0], argv);
    }
    else
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        //if(WIFEXITED(status) == 0) 这样不行啊，确实，看底层实现就明白
        if(WIFEXITED(status))//不对，再看
        //if(rid > 0)
        {
            lastcode = WEXITSTATUS(status);
        }
    }
}
char cwd[1024];
void cd(char* path)
{
    chdir(path);

    char tmp[1024];
    getcwd(tmp, sizeof tmp);
    sprintf(cwd, "PWD=%s", tmp);
    //下面这样会乱码，为什么 
    //getcwd(cwd, sizeof cwd);
    //sprintf(cwd, "PWD=%s", cwd);这个函数是直接往cwd里写，导致前缀被覆盖

    putenv(cwd);
}

char myenv[100];
int dobuildin(char* argv[])
{
    if(strcmp(argv[0], "cd") == 0)
    {
        char* path = NULL;
        if(argv[1]) path = argv[1];
        else path = getenv("HOME");
        cd(path);
        return 1;
    }
    else if(strcmp(argv[0], "export") == 0)
    {
        if(argv[1] == NULL) return 1;
        strcpy(myenv, argv[1]);
        putenv(myenv);
        return 1;
    }
    else if(strcmp(argv[0], "echo") == 0)
    {

//#ifdef DEBUG
//    for(size_t i = 0; argv[i]; i++)
//        printf("IFDEF:%s\n", argv[i]);//为什么不打印？
//#endif                            //因为return 写到ifdef上面了
        //printf("%s\n",filename );
        int fd = 0;
        if(redir == INPUTREDIR)
        {
            fd = open(filename, O_RDONLY);
            dup2(fd, 0); 
        }
        else if(redir == OUTPUTREDIR)
        {
            fd = open(filename, O_TRUNC|O_CREAT|O_WRONLY, 0666);
       // printf("fd%s\n",filename );
            
            dup2(fd, 1);
       // printf("dup2%s\n",filename );
        }
        else if(redir == APPENDREDIR)
        {
            fd = open(filename, O_APPEND|O_CREAT|O_WRONLY, 0666);
            dup2(fd, 1);
        }
        //printf("%s\n",filename );
        if(argv[1] == NULL)
        {
            printf("\n");
            return 1; //必须要return 1 不然下面的else没意义了
        }
        if(*argv[1] == '$' && strlen(argv[1]) > 1)
        {
            char* val = argv[1] + 1;
            if(strcmp(val, "?") == 0) //原来是这里 ,弄的我以为argv[1]为0
            {
                printf("%d\n", lastcode);
                lastcode = 0;
            }
            else
            {
                const char* _env = getenv(val);
                //const char* _env = getenv(argv[1]);

                if(_env) printf("%s\n", _env);
                else printf("\n");
            }
        }
        else 
        {
            printf("%s\n", argv[1]);
        }
        return 1;
    }
    return 0;
}


#define SKIPSPACE(pos) do{ while(*pos == ' ') pos++; }while(0)
void checkRedir(char command[])
{
    char* start = command;
    char* end = command + strlen(command) - 1;
    while(start < end)
    {
        if(*end == '>')
        {
             if(end - start > 0 && *(end - 1) == '>')
             {
                 redir = APPENDREDIR;
                 *(end - 1) = '\0';
                 // filename = end + 1;
                 // SKIPSPACE(filename);
                 //++end; 
                 //SKIPSPACE(end);
                 SKIPSPACE(++end);//这样不行，这样整个pos都会变成++end,因为只是宏
                 filename = end;
                 break;
             }
             else 
             {
                 redir = OUTPUTREDIR;
                 *end = '\0';
                 filename = strtok(end + 1, STRTOK_CH);
                  
                 break;
             }
        }
        else if(*end == '<')
        {
            redir = INPUTREDIR;
            *end = '\0';
            filename = end + 1;
            SKIPSPACE(filename);
            break;
        }
        else
        {
            end--;
        }
    }
}
//void changeRedir()   //这就是个bug，这里函数结束就被关了
//{
//    int fd = 0;
//    if(redir == INPUTREDIR)
//    {
//        fd = open(filename, O_RDONLY);
//        dup2(fd, 0); 
//    }
//    else if(redir == OUTPUTREDIR)
//    {
//        fd = open(filename, O_TRUNC|O_CREAT|O_WRONLY, 0666);
//        dup2(fd, 1);
//    }
//    else if(redir == APPENDREDIR)
//    {
//        fd = open(filename, O_APPEND|O_CREAT|O_WRONLY, 0666);
//        dup2(fd, 1);
//    }
//}
int main()
{
    while(1)
    {
        redir = NONEREDIR;
        filename = NULL;
        char command[COMMAND_LEN];
        printCommand();
        int n = getCommand(command);
        if(n == 0) continue;
        checkRedir(command);
        //changeRedir();
        char* argv[ARGV_LEN];
        splitCommand(command, argv);
        if(n <= 0) continue;
        n = dobuildin(argv);
        if(n == 1) continue;
        excuteSubProcess(argv);
    }
}
